/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int widthOfBinaryTree(TreeNode root) {
        // 层序遍历
        Queue<TreeNode> queue = new LinkedList<>();
        // 建立映射数组，添加结点索引
        LinkedList<Integer> index = new LinkedList<>();
        int max = 1;
        queue.offer(root);
        index.add(0);
        while(!queue.isEmpty()){
            int size = queue.size();
            max = Math.max(index.peekLast() - index.peekFirst() + 1, max);
            while(size-- > 0){
                TreeNode curNode = queue.poll();
                int curIndex = index.remove();

                if(curNode.left != null){
                    index.add(curIndex * 2 + 1);
                    queue.offer(curNode.left);
                }
                if(curNode.right != null){
                    index.add(curIndex * 2 + 2);
                    queue.offer(curNode.right);
                }
            }
        }
        return max;
    }
}